package grpc_module

import (
	"context"
	"gitee.com/kmyss/gf-ex/yscmd"
	"gitee.com/kmyss/gf-ex/yslog"
	"gitee.com/kmyss/ys-cli/internal/model"
	"gitee.com/kmyss/ys-cli/internal/service"
	"github.com/gogf/gf/v2/container/gmap"
)

type Builder struct {
	yscmd.CommandBuilderCore
}

func (b *Builder) Init(ctx context.Context) {
	b.CommandBuilderCore.Init(ctx)
	b.C.Use = "grpc-module"
	b.C.Short = "启动 YS-MQ 的模块"
	b.C.Long = `
    -- 文件管理
	-- 配置管理
	-- 监视器`

	b.C.Run = run
	b.addFlag()
}

func (b *Builder) addFlag() {
	b.SetFlag(&yscmd.FlagDebugBuilder{})
}

func run(c *yscmd.Command) {
	file := FlagFile(c.Context())
	fileParam := gmap.NewStrAnyMap()
	fileParam.Set("path", file.Get())

	watch := FlagWatch(c.Context())
	watchParam := gmap.NewStrAnyMap()
	watchParam.Set("topics", watch.Get())

	config := FlagConfig(c.Context())
	configParam := gmap.NewStrAnyMap()
	configParam.Set("path", config.Get())

	err := service.GrpcModule().Run(c.Context(), &model.GrpcModuleCfgInput{
		RunFile: model.GrpcModuleCfgNormal{
			Has:   file.Has(),
			Param: fileParam,
		},
		RunWatch: model.GrpcModuleCfgNormal{
			Has:   watch.Has(),
			Param: watchParam,
		},
		RunConfig: model.GrpcModuleCfgNormal{
			Has:   config.Has(),
			Param: configParam,
		},
	})
	if err != nil {
		yslog.Error("GRPC 模块启动失败！", err)
		yscmd.CmdWait(c.Context())
		return
	}

	yscmd.TimeToCloseShell(c.Context(), 2)
}

func GrpcModule(ctx context.Context) *yscmd.Command {
	c := &Builder{}
	c.Init(ctx)
	return c.Command()
}
